home *** CD-ROM | disk | FTP | other *** search
/ Tech Arsenal 1 / Tech Arsenal (Arsenal Computer).ISO / tek-01 / snip1292.zip / CHGEXT.C < prev    next >
C/C++ Source or Header  |  1992-12-26  |  2KB  |  72 lines

  1. /*
  2. **  chgext.c - Change a file's extension
  3. **
  4. **  public domain by Bob Stout
  5. **
  6. **  Arguments: 1 - Pathname
  7. **             2 - Old extension (NULL if don't care)
  8. **             3 - New extension
  9. **
  10. **  Returns: Pathname or NULL if failed
  11. **
  12. **  Note: Pathname buffer must be long enough to append new extension
  13. **
  14. **  Side effect: Converts Unix style pathnames to DOS style
  15. */
  16.  
  17. #include <stdio.h>
  18. #include <string.h>
  19.  
  20. char *chgext(char *path, char *oldext, char *newext)
  21. {
  22.       char *p;
  23.  
  24.       /* Convert to DOS-style path name */
  25.  
  26.       for (p = path; *p; ++p)
  27.             if ('/' == *p)
  28.                   *p = '\\';
  29.  
  30.       /* Find extension or point to end for appending */
  31.  
  32.       if (NULL == (p = strrchr(path, '.')) || NULL != strchr(p, '\\'))
  33.             p = strcpy(&path[strlen(path)], ".");
  34.       ++p;
  35.  
  36.       /* Check for old extension */
  37.  
  38.       if (oldext && strcmp(p, oldext))
  39.             return NULL;
  40.  
  41.       /* Add new extension */
  42.  
  43.       while ('.' == *newext)
  44.             ++newext;
  45.       strncpy(p, newext, 3);
  46.       return path;
  47. }
  48.  
  49. #ifdef TEST
  50.  
  51. void main(int argc, char *argv[])
  52. {
  53.       char *retval, *old_ext = NULL, path[128];
  54.  
  55.       if (2 > argc)
  56.       {
  57.             puts("Usage: CHGEXT path [old_ext]");
  58.             puts("\nChanges extension to \".TST\"");
  59.             puts("Old extension optional");
  60.             return;
  61.       }
  62.       strcpy(path, strupr(argv[1]));
  63.       if (2 < argc)
  64.             old_ext = strupr(argv[2]);
  65.       if (NULL == (retval = chgext(path, old_ext, ".TSTstuff")))
  66.             puts("chgext() failed");
  67.       else  printf("chgext(%s, %s, TST)\n...returned...\n%s\n", argv[1],
  68.             old_ext ? old_ext : "NULL", path);
  69. }
  70.  
  71. #endif /* TEST */
  72.